package com.ilink.ilinkuser.controller;

import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.service.oss.MinioService;
import com.ilink.ilinkcommon.service.oss.OssService;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user/certificate")
public class UserCertificateController {

    private final MinioService minioService;

    @MethodLog("生成证书图片")
    @GetMapping("/get")
    public R generateCertificate(@RequestParam String templateId, @RequestParam String name) {
        try {
            // 如果templateId是baidu，直接返回字符串"百度"
            if ("baidu".equals(templateId)) {
                String projectImageUrl = minioService.generatePresignedUrl("第一期训练营百度证书/"+name+".jpg","dataset-square-migrate");
                String newUrl = projectImageUrl.replace("http://10.3.244.23:19000/", "https://ilink.bupt.edu.cn/minio/");
                return R.ok(newUrl);
            }

            // 加载图片模板
            Resource resource = new ClassPathResource("templates/" + templateId + ".png");
            BufferedImage image = ImageIO.read(resource.getInputStream());
            if (image == null) {
                log.error("加载模板图片失败，模板ID: {}", templateId);
                return R.error("模板图片加载失败");
            }

            String fontPath = "fonts/Dengb.ttf"; // 自定义字体路径，放置在 classpath 下的 fonts 文件夹
            Font font ; // 加载字体并设置大小为 40
            // 根据templateId调整字体大小
            if ("ali".equals(templateId)) {
                font = loadFontFromClasspath(fontPath, 20); // 设置字体大小为 20
            } else {
                font = loadFontFromClasspath(fontPath, 40); // 默认字体大小为 40
            }
            if (font == null) {
                log.error("加载字体失败，字体路径: {}", fontPath);
                return R.error("字体加载失败");
            }

            // 在图片上绘制名字
            Graphics2D graphics = image.createGraphics();
            graphics.setFont(font);
            graphics.setColor(Color.BLACK);

            // 根据templateId调整文字位置
            if ("ali".equals(templateId)) {
                graphics.drawString(name, 500, 834);  // 假设位置需要调整
            } else {
                graphics.drawString(name + "同学：", 200, 710);  // 默认位置
            }

            // 将生成的图片转换为字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            byte[] imageBytes = baos.toByteArray();
            baos.close();

            log.info("证书图片生成成功，模板ID: {}, 姓名: {}", templateId, name);

            // 返回字节流给前端
            return R.ok("证书图片生成成功", imageBytes);
        } catch (IOException e) {
            log.error("证书图片生成失败，模板ID: {}, 错误信息: {}", templateId, e.getMessage());
            return R.error("证书图片生成失败");
        } catch (FontFormatException e) {
            throw new RuntimeException(e);
        }
    }

    private Font loadFontFromClasspath(String fontPath, float fontSize) throws IOException, FontFormatException {
        Resource resource = new ClassPathResource(fontPath);
        try (InputStream fontStream = resource.getInputStream()) {
            Font font = Font.createFont(Font.TRUETYPE_FONT, fontStream);
            return font.deriveFont(fontSize);
        }
    }
}
